# _*_ coding:utf-8 _*_
# @Time  : 2022.10.13
# @Author: zizlee
import time

import requests
from urllib3 import disable_warnings
from iFinDPy import THS_iFinDLogin, THS_iFinDLogout, THS_Date_Query, THS_BD
disable_warnings()

HOST = 'https://210.13.218.130:9000/'


def get_dates():
    ret = THS_Date_Query('212001', 'mode:1,dateType:0,period:D,dateFormat:0', '1991-01-02', '2021-12-31')  # 1991-01-01
    dates = ret.data
    return dates.split(',')


def get_total_block(query_date):  # 获取该日A股市场总市值
    ret = THS_BD('001005010', 'ths_mv_total_block', query_date)
    df = ret.data
    value = df.to_dict(orient='records')[0]['ths_mv_total_block']
    return 6440, [{'datadate': query_date, 'datavalue': round(value / pow(10, 8), 4)}]


def get_total_float_block(query_date):  # 获取该日A股市场总流通市值
    ret = THS_BD('001005010', 'ths_flaot_mv_sum_block', query_date)
    df = ret.data
    value = df.to_dict(orient='records')[0]['ths_flaot_mv_sum_block']
    return 6441, [{'datadate': query_date, 'datavalue': round(value / pow(10, 8), 4)}]


def get_total_amt(query_date):  # 获取该日全部A股的总成交额
    ret = THS_BD('001005010', 'ths_amt_sum_block', query_date)
    df = ret.data
    value = df.to_dict(orient='records')[0]['ths_amt_sum_block']
    return 6442, [{'datadate': query_date, 'datavalue': round(value / pow(10, 8), 4)}]


def get_pe_ttm_index(index_code, query_date):  # 获取指数市盈率ttm整体法剔除负值
    # 上证指数:000001.SH  1991-01-03
    # 深证成指:399001.SZ  1995-02-01
    # 创业扳指：399006.SZ 2010-06-01
    ids = {
        '000001.SH': 6443,
        '399001.SZ': 6444,
        '399006.SZ': 6445,
    }
    ret = THS_BD(index_code, 'ths_pe_ttm_index', f'{query_date},101,100')
    df = ret.data
    value = df.to_dict(orient='records')[0]['ths_pe_ttm_index']
    if value:
        value = round(value, 4)
    return ids[index_code], [{'datadate': query_date, 'datavalue': value}]


def get_pb_index(index_code, query_date):  # 获取指数市净率
    # 上证指数:000001.SH  1991-01-03
    # 深证成指:399001.SZ  1995-02-01
    # 创业扳指：399006.SZ 2010-06-01
    ids = {
        '000001.SH': 6446,
        '399001.SZ': 6447,
        '399006.SZ': 6448,
    }
    ret = THS_BD(index_code, 'ths_pb_index', f'{query_date},100,100')
    df = ret.data
    value = df.to_dict(orient='records')[0]['ths_pb_index']
    if value:
        value = round(value, 4)
    return ids[index_code], [{'datadate': query_date, 'datavalue': value}]


def save_ths_values(sheet_id, datalist):
    url = HOST + 'v1/datalib/table/update/'
    body_data = {'dataid': sheet_id, 'row_value': datalist}
    r = requests.post(url, json=body_data, verify=False)
    print(r.json())


if __name__ == '__main__':
    # THS_iFinDLogin('rdqh085', '666888')
    # date_list = get_dates()
    # for d in date_list:
    #     index_id, values = get_total_block(d)
    #     print(d, values)
    #     if values[0]['datavalue'] is None:
    #         continue
    #     save_ths_values(index_id, values)
    #     time.sleep(0.4)
    # THS_iFinDLogout()
    pass  # 不需要了

